package STUDIO.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import STUDIO.excepcion.DAOStudioExcepcion;
import STUDIO.modelo.Ser_Adi;
import STUDIO.util.CONEXIONStudioBD;


public class Ser_AdiDAO extends BaseStudioDAO {

	public Ser_Adi insertar(Ser_Adi vo) throws DAOStudioExcepcion {

		System.out.println("Ser_AdiDAO: insertar()");
		String query = "INSERT INTO servicios_adic (tipo_servicio,costo_servicio,reserva_sala_idreserva_sala,administrador_idadmin) VALUES (?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

		try {
			con = CONEXIONStudioBD.obtenerConexion();
			//con.setAutoCommit(false);
			stmt = con.prepareStatement(query);
			stmt.setString(1, vo.getTipo_servicio());
			stmt.setString(2, vo.getCosto_servicio());
			stmt.setInt(3, vo.getReserva().getId_reserva_sala());
			stmt.setInt(4,vo.getAdministrador().getIdadmin());
			System.out.println(query);
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("No se pudo insertar Servico Adicional");
			}

			int idp = 0;
			//se hace para saber el ultimo id
			query = "SELECT LAST_INSERT_ID()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				idp = rs.getInt(1);
			}
			vo.setId_servicios(idp);
			//
			//con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				throw new DAOStudioExcepcion(e.getMessage());
			}
			System.err.println(e.getMessage());
			throw new DAOStudioExcepcion(e.getMessage());
		} finally {
			try {
				con.setAutoCommit(true);
			} catch (SQLException e) {
				throw new DAOStudioExcepcion(e.getMessage());
			}
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return vo;
	}

}
